// pages/settings/settings.js
import {
    Product
} from 'product-model.js'
var product = new Product();
//获取应用实例
const app = getApp()
Page({
    /**
     * 页面的初始数据
     */
    data: {
        productDetail: null,
        current: 0, //当前进度条位置
        percent: 0, //轮播图总长度
        ctrnum: 1, //当前选中购买数量
        stockNum: null, //共有衣服件数
        specsName: "", //选择尺寸
        isShowPopup: false,
        tip: "",
        cartNum: 0,
        animate: false, //购物车动画
        sellOut: 1, //商品是否售罄
        current: 0,
        orderConfirm: true, //是否可点击去付款
        isVip: 0,
        isShowCountDown: false,
        isScroll:false,
        discount:0,
        nowVideo: '',
        needShow:false
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        let sessionId = wx.getStorageSync("sessionId");
        //获取分享人的手机号

        let id = options.id;
        let storeNo = wx.getStorageSync('storeNo');
        
        if (options && options.invitePhone) {
            console.log('通过会员邀请人手机号', options.invitePhone)
            wx.setStorageSync("invitePhone", options.invitePhone);
        }
        // 扫描播货二维码进来
        if (options && options.scene) {
            var scene = decodeURIComponent(options.scene);
            if (scene != 'undefined' && scene != null) {

                var sceneList = scene.split(',');
                console.log('二维码', sceneList)
                id = sceneList[0];
                let inviteCode = sceneList[1];
                this.setData({
                    inviteCode
                })
                wx.setStorageSync('inviteCode', inviteCode);
                let params = {
                    inviteCode
                }
                if (sessionId !== "") {
                    // 绑定邀请码
                    product.bindInviteCodeByMiniProgram(params, res => {
                        console.log('商品详情二维码绑定邀请码')   
                        if (res.status) {
                            console.log('商品详情二维码绑定邀请码成功')
                        }
                    })
                }
            }
        }
        // 通过代购直接分享小程序进来
        if (options && options.inviteDaigoCode) {
            let params = {
                inviteCode: options.inviteDaigoCode
            }
            // 代购推广使用
            wx.setStorageSync('inviteCode', options.inviteDaigoCode)
            console.log('通过代购直接分享小程序进来inviteCode', wx.getStorageSync('inviteCode'))
            if (sessionId !== "") {
                // 绑定邀请码
                product.bindInviteCodeByMiniProgram(params, res => {
                    console.log('商品详情卡片绑定邀请码',res)
                    if (res.status) {
                        console.log('商品详情卡片绑定邀请码成功')
                    }
                })
            }
        }
        this.setData({
            storeNo,
            goodsId: id
        });
        //如果没登录需要跳转到登录页面
        if (sessionId === '') {
            let inviteCode = wx.getStorageSync('inviteCode');            
            wx.redirectTo({
                url: '/pages/getUserInfo/getUserInfo?path=/pages/product/product&id=' + id + '&inviteDaigoCode=' + inviteCode
            })
            return
        }
        app.aldstat.sendEvent('进入商品详情页面');
        wx.showLoading({
            title: '加载中...',
        })
        this._loadData();
        
    },
    onShow() {
        this.setData({
            isVip: wx.getStorageSync('userStatus'),
            needShow: wx.getStorageSync('needShow') == product.nowV ? false : true  
            
        })
    },
    _loadData(cb) {
        this.getGoodDetail(cb);
        this.getCart();
    },
    //获取商品详情
    getGoodDetail(cb) {
        let {
            storeNo,
            goodsId
        } = this.data;
        let parames = {
            "storeNo": storeNo.toString(),
            "goodsId": '' + goodsId,
            "userStatus": wx.getStorageSync('userStatus')
        };
        let that = this;
        let timer;
        product.getGoodsById(parames, res => {
            if (res.status) {
                let data = res.data;
                data.nowTime = new Date().getTime()
                that.setData({
                    loadingHidden: true
                })
                let percent = data.goodsImages.length; //设置滚动条
                let goodsId = data.goodsId;
                let discount = that.returnFloat ((data.memberPrice / data.goodsPrice)*10)
                //判断是否还有库存
                let total = 0;
                data.goodsStock.forEach((value, index) => {
                    total += value.stockNum;
                })
                data.goodsColour.forEach((value, index) => {
                    if (value.goods_id == goodsId) {
                        value.isSelected = true;
                    }
                })
                if (data.goodsStock.length === 1){
                    this.setData({
                        stockNum: data.goodsStock[0].stockNum,
                        specsName: data.goodsStock[0].specsName
                    })
                    data.goodsStock[0].isSelected = true; //选中尺寸第一个
                    this.setData({
                        productDetail: data,
                        percent,
                        sellOut: total,
                        discount
                    })
                }else{
                    this.setData({
                        productDetail: data,
                        percent,               
                        sellOut: total,
                        stockNum: 0,
                        specsName: '',
                        discount
                    })
                }
               

                // 倒计时
                let nowDate = new Date().getTime();
                if (nowDate < data.startTime) {
                    this.setData({
                        isShowCountDown: true
                    })
                    clearInterval(timer)
                    this.countDown()
                    timer = setInterval(() => {
                        this.countDown(()=>{
                            nowDate = new Date().getTime();
                            if (nowDate >= data.startTime){
                                this.setData({
                                    isShowCountDown: false
                                })
                                clearInterval(timer)
                                this.getGoodDetail()
                            }
                        })
                    }, 1000)
                }
                cb && cb();
                wx.hideLoading();
            } else {
                wx.showToast({
                    title: '操作错误，可能该商品不存在',
                    icon: 'none'
                })
            }
        });
    },
    //获取购物车数据
    getCart(cb) {
        let that = this;
        let {
            storeNo
        } = this.data;
        let userInfo = wx.getStorageSync('sessionId');
        if (userInfo) {
            let parames = {
                "userId": this.toString(userInfo.id),
                "storeNo": this.toString(storeNo)
            }
            product.getCart(parames, res => {
                if (res.status) {
                    let total = 0;
                    res.data.forEach((value, index) => {
                        value.list.forEach((val, index) => {
                            total += parseInt(val.goodsNum);
                        });
                    })

                    that.setData({
                        "cartNum": total
                    })
                    cb && cb();
                    //设置购物车右上角红色点
                    wx.setTabBarBadge({
                        index: 1,
                        text: '' + total,
                    })

                }
            })
        }

    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        wx.showNavigationBarLoading(); //在标题栏中显示加载图标 
        this._loadData(() => {
            wx.hideNavigationBarLoading();
            wx.stopPullDownRefresh(); //停止下拉刷新 
        })

    },
    onColorOption: function (e) {
        let goodsId = product.getDataSet(e, "goodid");
        let curGoodsId = this.data.productDetail.goodsId;
        if (curGoodsId != goodsId) {
            this.setData({
                "goodsId": goodsId,
                stockNum: null,
                current: 0
            });
            this.getGoodDetail();
        }
    },
    onHeadChange(e) {
        let current = e.detail.current;
        this.setData({
            current
        })
    },
    onSizeOption(e) {
        let id = product.getDataSet(e, "id");
        let {
            productDetail,
            ctrnum
        } = this.data;
        let stockNum = 0;
        let specsName = "";
        productDetail.goodsStock.forEach((value, index) => {
            if (value.id == id) {

                value.isSelected = value.isSelected ? false : true;
                if (value.isSelected) {
                    stockNum = value.stockNum;
                    specsName = value.specsName;
                    if (ctrnum <= 0) {
                        ctrnum = 1;
                    }
                } else {
                    stockNum = 0;
                    specsName = "";
                }
            } else {
                value.isSelected = false;
            }
        });

        if (ctrnum > stockNum) {
            ctrnum = stockNum
        }

        this.setData({
            "productDetail.goodsStock": productDetail.goodsStock,
            stockNum,
            specsName,
            ctrnum
        })

    },
    //加入购物车
    onAddCart(e) {
        let that = this;
        app.aldstat.sendEvent('加入预购清单-商品详情');
        let userInfo = wx.getStorageSync('sessionId');
        //此处需要判断用户是否存在
        this.getUserInfo(userInfo);
        let {
            storeNo,
            productDetail,
            ctrnum,
            specsName,
            isVip,
            isScroll
        } = this.data;
        if(!isScroll){
            wx.pageScrollTo({
                scrollTop: 200,
                duration: 200
            })
            this.setData({
                isScroll:true
            })
        }
        if (userInfo) {
            let parames = {
                "storeNo": '' + storeNo,
                "goodsId": '' + productDetail.goodsId,
                "goodsName": '' + productDetail.goodsName,
                "goodsPic": '' + productDetail.goodsPic,
                "goodsPrice": '' + (isVip == 0 ? productDetail.discountPrice :
                    ((productDetail.memberPrice && productDetail.memberPrice != '') ? productDetail.memberPrice : productDetail.discountPrice)),
                "originalPrice": '' + productDetail.goodsPrice,
                "goodsNum": '' + ctrnum,
                "goodsColor": '' + productDetail.goodsColor,
                "specsName": '' + specsName,
                "originalPrice": '' + productDetail.goodsPrice,
                "activityId": "" + productDetail.activityId,
                "discountPrice": "" + productDetail.discountPrice,
            }
            if (isVip > 0) {
                parames.memberPrice = '' + productDetail.memberPrice
            }
            if (parames.specsName == "") {
                wx.showToast({
                    title: '请选择商品尺寸',
                    icon: 'none'
                })
                return;
            }
            if (parames.goodsNum == "0") {
                wx.showToast({
                    title: '商品数量不能为0',
                    icon: 'none'
                })
                return;
            }
            product.addCart(parames, res => {
                if (res.status) {
                    wx.showToast({
                        title: '加入购物车成功',
                    })
                    let {cartNum} = this.data
                    this.setData({
                        cartNum: ctrnum + cartNum
                    })
                    that.setData({
                        animate: true
                    })
                    setTimeout(() => {
                        that.setData({
                            animate: false
                        });
                    }, 500)
                } else {

                    wx.showToast({
                        title: '加入购物车失败',
                        icon: 'none'
                    })
                }
            })
        }
    },
    //进入购物车
    goCart() {
        wx.switchTab({
            url: '/pages/cart/cart'
        })
    },
    //去付款 立即抢购
    onOrderConfirm(e) {
        app.aldstat.sendEvent('立即抢购-商品详情');
        let userInfo = this.data.userInfo || wx.getStorageSync('sessionId');
        let phone = wx.getStorageSync('phone');
        let {
            productDetail,
            specsName,
            ctrnum,
            storeNo,
            goodsId,
            isScroll
        } = this.data;
        if (phone === '') {
            wx.navigateTo({
                url: '/pages/signin/signin?path=/pages/product/product&id=' + goodsId,
            })
            return
        }
        //此处需要判断用户是否存在
        this.getUserInfo(userInfo);
        let that = this;
        if (userInfo) {
            let result = [];

            result.push({
                "storeNo": this.toString(storeNo),
                "specsName": this.toString(specsName),
                "goodsId": this.toString(productDetail.goodsId)
            });

            if (result[0].specsName == "") {
                if (!isScroll) {
                    wx.pageScrollTo({
                        scrollTop: 200,
                        duration: 200
                    })
                    this.setData({
                        isScroll: true
                    })
                }
                wx.showToast({
                    title: '请选择商品尺寸',
                    icon: 'none'
                })
                return;
            }
            this.setData({
                orderConfirm: false
            })
            wx.showLoading({
                title: '加载中...',
            })
            let params = {
                "storeNo": storeNo,
                "goodsId": '' + productDetail.goodsId,
                "goodsName": productDetail.goodsName,
                "goodsNum": '' + ctrnum,
                "goodsPrice": '' + productDetail.goodsPrice,
                "goodsColor": '' + productDetail.goodsColor,
                "specsName": '' + specsName,
                "goodsPic": '' + productDetail.goodsPic,
                "activityId": '' + productDetail.activityId
            };
            console.log(params)
            product.nowBuy(params, res => {
                that.setData({
                    orderConfirm: true
                })
                wx.hideLoading();
                if (res.status) {

                    wx.navigateTo({
                        url: "/pages/orderDetail/orderDetail?orderId=" + res.data.orderId
                    })
                } else {
                    wx.showToast({
                        title: res.message,
                        icon: 'none'
                    })
                }
            })
        }


    },
    //判断用户信息是否存在
    getUserInfo(userInfo) {
        if (!userInfo) {
            let parames = {
                _content: "请先完成登录",
                confirm: () => {
                    wx.navigateTo({
                        url: '/pages/login/login',
                    })
                },
                cancel: () => {
                    return;
                }
            }
            product.showModal(parames);
        } else {
            this.setData({
                userInfo: userInfo
            });
        }
    },
    toString(parames) {
        if (parames != null && parames != "") {
            return parames.toString();
        } else {
            return "";
        }
    },
    onNumMinus(e) {
        let ctrnum = this.data.ctrnum;
        if (ctrnum > 1) {
            ctrnum--;
            this.setData({
                ctrnum
            })
        } else {
            return;
        }
    },
    onNumAdd(e) {
        let {
            ctrnum,
            stockNum,
            specsName
        } = this.data;

        if (specsName == "") {
            wx.showToast({
                title: '请选择商品尺寸',
                icon: 'none'
            })
            return;
        }

        if (ctrnum < stockNum) {
            ctrnum++;
            this.setData({
                ctrnum
            })
        } else {
            wx.showToast({
                title: '数量已达上限',
                icon: 'none'
            })
            return;
        }
    },
    //   预览图片
    preImg(e) {
        let goodsImages = this.data.productDetail.goodsImages
        let now = product.getDataSet(e, "src")
        let imgList = []
        if (goodsImages || goodsImages.length > 0) {
            goodsImages && goodsImages.forEach(val => {
                imgList.push(val.url)
            })
            wx.previewImage({
                current: now, // 当前显示图片的http链接
                urls: imgList // 需要预览的图片http链接列表
            })
        }
    },
    /**
     * 用户点击右上角分享
     */

    onShareAppMessage: function () {
        app.aldstat.sendEvent('商品详情-分享');
        let productDetail = this.data.productDetail;
        // let phone = wx.getStorageSync('phone')
        wx.showShareMenu({
            withShareTicket: true
        });
        let phone = wx.getStorageSync('phone'),
            invitePhone = wx.getStorageSync('invitePhone'),
            inviteDaigoCode = wx.getStorageSync('inviteDaigoCode'),
            ownInviteCode = wx.getStorageSync('ownInviteCode'),
            userStatus = wx.getStorageSync('userStatus'),
            // 如果自己是代购以上身份就用自己邀请码，否则是上游邀请码
            nowInviteCode = userStatus > 1 ? ownInviteCode : inviteDaigoCode,
            path = '';  
        console.log('userStatus', userStatus, 'inviteDaigoCode', inviteDaigoCode, 'ownInviteCode', ownInviteCode)   
        if ((!userStatus || userStatus === 0) && nowInviteCode) {
            path = `&inviteDaigoCode=${nowInviteCode}`
        } else if (userStatus === 1) {
            path = `&invitePhone=${phone}`
        } else if (userStatus > 1) {
            path = `&inviteDaigoCode=${nowInviteCode}`
        }
        return {
            title: productDetail.goodsName + ' 会员价:￥' + productDetail.memberPrice, //storeInfo.brandName,
            path: `/pages/product/product?id=${productDetail.goodsId}${path}` ,
            success: res => {
                if (res.shareTickets) {
                    console.log(res.shareTickets);
                    wx.getShareInfo({
                        shareTicket: res.shareTickets[0],
                        success: d => {
                            console.log(d);
                        }
                    })
                }
            }
        }
    },
    // 定时器
    countDown(cb) {
        let {
            productDetail
        } = this.data
        let date = new Date();
        let aDay = 24 * 60 * 60 * 1000; //一天时间

        let startTime = productDetail.startTime;
        var diffDay = (startTime - date) / aDay;
        if (diffDay >= 1) {
            productDetail.diffDay = parseInt(diffDay)
        } else {
            productDetail.diffDay = 0
        }
        productDetail.clock = product.countdown(startTime)
        let { hour, minute, second } = productDetail.clock
        cb && cb()
        this.setData({
            productDetail
        })

    },
    // 跳转购买会员页
    jumpOrdinary() {
        let phone = wx.getStorageSync("phone");
        let { goodsId } = this.data
        if (phone === "") {
            wx.navigateTo({
                url: '/pages/signin/signin?path=/pages/role/ordinary/ordinary',
            })
        } else {
            wx.navigateTo({
                url: '/pages/role/ordinary/ordinary',
            })
        }
    },
    goHome(){
      wx.switchTab({
        url: '/pages/index/index',
      })
    },
    //保留两位小数
    returnFloat: function (value) {
    //   var value = Math.round(parseFloat(value) * 100) / 100;
    //   var xsd = value.toString().split(".");
    //   if (xsd.length == 1) {
    //     value = value.toString() + ".0";
    //     return value;
    //   }
    //   if (xsd.length > 1) {
    //     if (xsd[1].length < 2) {
    //       value = value.toString() ;
    //     }
    //     return value;
    //   }
        return value.toFixed(1)
    },
    activityTips(e){
        let status = product.getDataSet(e,'status');
        if(status == 2){
            wx.showToast({
                title: '该活动已结束',
                icon: 'none'
            })
        }
    },
    onReady: function (res) {
        this.videoContext = wx.createVideoContext('myVideo')
    },
    showVideo(e) {
        let url = this.data.productDetail.videoUrl
        this.setData({
            nowVideo: url
        })
        this.videoContext.requestFullScreen({ direction: 0 })
    },
    bindfullscreenchange(e) {
        console.log(e.detail)
        if (e.detail.fullScreen) {
            this.videoContext.play()
        } else {
            this.videoContext.pause()
        }
    },
    outFullScreen() {
        this.videoContext.pause()
        this.videoContext.exitFullScreen()
    },

})